package com.anti.jdbc.support.mapper;

/**
 * @Description TODO
 * @Author anTi
 * @Date 2020-10-6
 */

import com.anti.commom.core.utils.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;

public class MapRowMapper implements RowMapper<Map<String, Object>> {
    private String[] columnname;
    public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Map<String, Object> mapOfColValues = new LinkedHashMap(columnCount);
        boolean firstRow = false;
        if (this.columnname == null) {
            firstRow = true;
            this.columnname = new String[columnCount];
        }

        for(int i = 1; i <= columnCount; ++i) {
            if (firstRow) {
                this.columnname[i - 1] = this.getColumnKey(JdbcUtils.lookupColumnName(rsmd, i));
            }

            String key = this.columnname[i - 1];
            Object obj = this.getColumnValue(rs, i);
            mapOfColValues.put(key, obj);
        }

        return mapOfColValues;
    }

    /**
     * 列明获取规则
     * @param columnName
     * @return
     */
    protected String getColumnKey(String columnName) {
        //switch(ConfigHolder.getDbFiledMapMethod()) {
        switch(0) {
            case 0:
                return StringUtils.toCamelCase(columnName);
            case 1:
                columnName = StringUtils.toLowerCase(columnName);
                return StringUtils.remove(columnName, '_');
            default:
                return columnName;
        }
    }

    protected Object getColumnValue(ResultSet rs, int index) throws SQLException {
        return JdbcUtils.getResultSetValue(rs, index);
    }
}
